<template>
  <div class="role-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon">
            <i class="el-icon-s-order" />
          </el-icon>
          羊只采购
        </h1>
        <p class="page-description">管理羊只采购信息，支持条件查询与分页</p>
      </div>
    </div>

    <!-- 主要内容卡片 -->
    <el-card class="main-card" shadow="hover">
      <!-- 搜索和操作区域 -->
      <div class="action-section">
        <el-form :inline="true" :model="QueryInfo" class="search-form">
          <el-form-item label="采购员">
            <el-select v-model="QueryInfo.PurchaserId" placeholder="请选择采购员" filterable>
              <el-option v-for="item in purchaserList" :key="item.UserId" :label="item.UserName" :value="item.UserId" />
            </el-select>
          </el-form-item>
         
          <el-form-item label="采购日期">
            <el-date-picker v-model="QueryInfo.PurchaseDate" type="date" placeholder="请选择采购日期" style="width: 100%" clearable />
          </el-form-item>
          <el-form-item label="羊只类型">
            <el-select v-model="QueryInfo.SheepTypeId" placeholder="请选择羊只类型" clearable filterable>
              <el-option v-for="item in sheepTypeList" :key="item.Id" :label="item.TypeName || item.Name" :value="item.Id" />
            </el-select>
          </el-form-item>
          <el-form-item label="栋舍">
            <el-select v-model="QueryInfo.PenId" placeholder="请选择栋舍" clearable filterable>
              <el-option v-for="item in penList" :key="item.House_typeId" :label="item.DongsheName" :value="item.House_typeId" />
            </el-select>
          </el-form-item>
          <el-form-item label="耳号">
            <el-select v-model="QueryInfo.EarNumber" placeholder="请选择耳号" clearable filterable>
              <el-option v-for="item in earNumberOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item class="form-item">
            <el-button type="primary" @click="fetchList" class="action-btn search-btn" icon="el-icon-search">查询</el-button>
            <el-button type="success" @click="addPopup" class="action-btn add-btn" icon="el-icon-plus">新增采购</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table :data="tableData" style="width: 100%" border class="data-table" stripe highlight-current-row>
          <el-table-column type="index" label="编号" width="80" align="center" />
          <el-table-column prop="PurchaseDate" label="采购日期" width="160" align="center">
            <template #default="scope">
              {{ scope.row.PurchaseDate ? dayjs(scope.row.PurchaseDate).format('YYYY-MM-DD') : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="PurchaserName" label="采购员" width="120" align="center">
           
          </el-table-column>
          <el-table-column prop="SheepTypeName" label="羊只类型" width="120" align="center" />
          <el-table-column prop="EarNumber" label="耳号" width="120" align="center" />
          <el-table-column prop="PenName" label="栋舍" width="120" align="center" />
          <el-table-column prop="Gender" label="性别" width="80" align="center">
            
            
            
          </el-table-column>
          <el-table-column prop="Tag" label="标签" width="100" align="center" />
          <el-table-column prop="Unit" label="单位" width="100" align="center" />
          <el-table-column prop="Quantity" label="数量" width="100" align="center">
            
          </el-table-column>
          <el-table-column prop="UnitPrice" label="单价" width="100" align="center">
           
          </el-table-column>
          <el-table-column prop="Amount" label="金额" width="100" align="center" />
          <el-table-column prop="Discount" label="折扣" width="100" align="center" />
          <el-table-column prop="FinalAmount" label="结算金额" width="120" align="center" />
          <el-table-column prop="CreateTime" label="创建时间" width="160" align="center">
            <template #default="scope">
              {{ scope.row.CreateTime ? dayjs(scope.row.CreateTime).format('YYYY-MM-DD') : '' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="140" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button link type="danger" size="small" @click="deletePurchase(scope.row)" class="delete-btn" icon="el-icon-delete">删除</el-button>
                <el-button link type="primary" size="small" @click="editPurchase(scope.row)" class="edit-btn" icon="el-icon-edit">修改</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="QueryInfo.PageIndex"
          v-model:page-size="QueryInfo.PageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Sheep_BreedingWrite, serviceRead } from '@/utils/Interceptors';
import { Sheep_BreedingRead } from '@/utils/Interceptors';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router'
import dayjs from 'dayjs';

const router = useRouter()

const earNumberOptions = ref<string[]>([]);
const fetchEarNumbers = () => {
  Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIDEarNumber').then(res => {
    earNumberOptions.value = (res.data.data || []).map((item: any) => item.Name);
  });
};

const QueryInfo = reactive({
  PageIndex: 1,
  PageSize: 10,
  PurchaserId: '',
  SheepTypeId: '',
  PenId: '',
  BatchNumber: '',
  PurchaseDate: '',
  EarNumber: ''
})
const totalCount = ref(0)

const tableData = ref<any[]>([])

// 下拉数据
const sheepTypeList = ref<any[]>([])
const penList = ref<any[]>([])
const purchaserList = ref<any[]>([])

const batchNumberOptions = ref<string[]>([]);
const fetchBatchNumbers = () => {
  Sheep_BreedingWrite.get('/api/SheepPurchase/search', { params: { PageIndex: 1, PageSize: 9999 } }).then(res => {
    // 假设返回结构为 res.data.data: [{ BatchNumber: 'B001', ... }, ...]
    const all = res.data.data || [];
    // 去重
    batchNumberOptions.value = Array.from(new Set(all.map((item: any) => item.BatchNumber).filter(Boolean)));
  });
};

// 获取羊只类型
const fetchSheepTypeList = () => {
  Sheep_BreedingWrite.get('/api/SheepType/List/list').then(res => {
    if (res.data && res.data.code === 200) {
      sheepTypeList.value = res.data.data || []
    } else {
      sheepTypeList.value = []
    }
  })
}
// 获取栋舍
const fetchPenList = () => {
  Sheep_BreedingWrite.get('/api/Pen/List').then(res => {
    if (res.data && res.data.code === 200) {
      penList.value = res.data.data || []
      // 自动打印返回内容，方便调试
      console.log('penList接口返回', penList.value)
    } else {
      penList.value = []
      console.log('penList接口无数据')
    }
  })
}

const fetchPurchaserList = () => {
  serviceRead.get('/api/User/SraechUser').then(res => {
    console.log('采购员接口返回', res.data);
    purchaserList.value = Array.isArray(res.data)
      ? res.data
      : res.data.PageData || res.data.data || [];
  });
}

// 查询采购列表
const fetchList = () => {
  // 格式化采购日期为字符串
  const params = {
    ...QueryInfo,
    PurchaseDate: QueryInfo.PurchaseDate
      ? dayjs(QueryInfo.PurchaseDate).format('YYYY-MM-DD')
      : ''
  };
  Sheep_BreedingWrite.get('/api/SheepPurchase/search', { params }).then(res => {
    if (res.data && res.data.code === 200) {
      tableData.value = res.data.data || []
      totalCount.value = (res.data.data && res.data.data.length) || 0
    } else {
      tableData.value = []
      totalCount.value = 0
    }
  })
}

const addPopup = () => {
  router.push({ name: 'PurchaseAddView' })
}

const deletePurchase = (row: any) => {
  ElMessageBox.confirm('是否删除当前采购信息？', '删除确认', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    Sheep_BreedingWrite.delete('/api/SheepPurchase/delete', { params: { Id: row.Id } }).then(res => {
      if (res.data && res.data.code === 200) {
        ElMessage.success(res.data.msg || '删除成功')
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
      fetchList() // 无论成功失败都刷新，防止前端残留
    })
  })
}

const editPurchase = (row: any) => {
  router.push({ name: 'PurchaseAddView', query: { id: row.Id } })
}

const handleSizeChange = (val: number) => {
  QueryInfo.PageSize = val
  fetchList()
}
const handleCurrentChange = (val: number) => {
  QueryInfo.PageIndex = val
  fetchList()
}

onMounted(() => {
  fetchSheepTypeList()
  fetchPenList()
  fetchPurchaserList()
  fetchList()
  fetchBatchNumbers();
  fetchEarNumbers();
})
</script>

<style scoped>
.role-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0;
}
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32px 0;
  margin-bottom: 24px;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.header-content {
  text-align: center;
  color: white;
}
.page-title {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}
.title-icon {
  font-size: 36px;
  color: #ffd700;
}
.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}
.main-card {
  margin: 0 24px;
  border-radius: 16px;
}
.action-section {
  margin-bottom: 18px;
}
.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 8px 24px;
}
.table-section {
  margin-bottom: 18px;
}
.data-table {
  border-radius: 12px;
}
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}
.pagination-section {
  margin-top: 18px;
  text-align: right;
}
.dialog-footer {
  text-align: right;
}
</style> 